<template>
  <div class="online-store-products">
    <el-form ref="form" :model="model" :rules="validatorRules" label-position="left" style="position: relative;">
      <div v-if="isDetails" class="mask" style="background-color: transparent;width: 100%;height: 100%;position: absolute;top: 0;left: 0;z-index: 9999;"></div>

      <div class="form_div top-label">
        <el-form-item label="网店商品名称" class="layoutOne" prop="goodsName">
          <el-input
            v-model="model.goodsName"
            placeholder="请输入网店商品名称"
            :class="{ 'name-warning': !isGoodsNameConsistent }"
            @input="onGoodsNameChange"
          ></el-input>
        </el-form-item>
        <el-form-item label="网店商品分类"  class="layoutTwo" prop="categoryId">
          <a-select v-model="model.categoryId" :getPopupContainer="getPopupContainer" placeholder="请选择商品分类" @change="clearValidate('categoryId')">
            <a-select-option v-for="item in categoryList" :key="item.categoryId" :value="item.categoryId">
              {{item.name}}
            </a-select-option>
          </a-select>
          <div class="form-item-help">
            <span @click="openCategoryDialog(1)">新增分类</span>
            <span style="margin-left: 20px" @click="refreshCategory(1)">刷新</span>
          </div>
        </el-form-item>
      </div>
      <div class="form_div" style="margin-top: 50px">
        <el-form-item label="商品状态" prop="status">
          <a-radio-group v-model="model.status">
            <a-radio :value="10">上架</a-radio>
            <a-radio :value="20">下架</a-radio>
          </a-radio-group>
        </el-form-item>
        <el-form-item label="网店排序值" prop="sort">
          <a-input-number style="width: 100%" v-model="model.sort" placeholder="请输入排序值"></a-input-number>
        </el-form-item>
        <el-form-item label="网店商品单位" prop="unitId">
          <a-select v-model="model.unitId" :getPopupContainer="getPopupContainer" placeholder="请选择商品单位" @change="clearValidate('unitId')" ref="unitSelect">
            <a-select-option v-for="item in jbdwOptions" :key="item.id" :value="item.id">
              {{item.unitName}}
            </a-select-option>
          </a-select>
        </el-form-item>
      </div>
      <div class="form_div top-label" style="height: auto">
        <el-form-item label="图文信息" prop="content" class="ml0">
          <div style="flex: 3;">
            <j-editor v-model="model.content" @input="clearValidate('content')" />
          </div>
          <div style="flex: 1;height: 300px;margin-left: 20px;position: relative;">
            <img style="width: 160px;height: 100%;" src="@/assets/xcx_wentu.png" alt="">
            <div class="content_div">
              <div v-html="model.content"></div>
            </div>
          </div>
        </el-form-item>
      </div>
      <!-- 单规格 -->
      <div class="form_div" v-if="model.specType == 10">
        <el-form-item label="规格类型" prop="specType" class="mr2">
          <a-radio-group v-model="model.specType">
            <a-radio :value="10">单规格</a-radio>
            <a-radio :value="20">多规格</a-radio>
          </a-radio-group>
        </el-form-item>
        <el-form-item label="库存计算方式" prop="deductStockType">
          <a-radio-group v-model="model.deductStockType">
            <a-radio :value="10">下单减库存</a-radio>
            <a-radio :value="20">付款减库存</a-radio>
          </a-radio-group>
        </el-form-item>
        <el-form-item label="网店商品库存">
          <a-input-number style="width: 100%" v-model="model.stockNum" placeholder="请输入商品库存"></a-input-number>
        </el-form-item>
        <!-- <el-form-item label="初始销量">
          <a-input-number
            style="width: 100%"
            :min="0"
            v-model="model.salesInitial"
            placeholder="请输入初始销量"
          ></a-input-number>
        </el-form-item> -->
      </div>
      <div class="form_div" v-if="model.specType == 10">
        <el-form-item label="网店商品原价" class="mr2">
          <a-input-number
            style="width: 100%"
            :min="0"
            v-model="model.linePrice"
            placeholder="请输入网店商品原价"
          ></a-input-number
          >&nbsp;元
        </el-form-item>
        <el-form-item label="网店商品优惠价" prop="goodsPrice">
          <a-input-number
            style="width: 100%"
            v-model="model.goodsPrice"
            :min="0.01"
            :max="1000000"
            step="0.01"
            placeholder="请输入网店商品优惠价"
          ></a-input-number
          >&nbsp;元
        </el-form-item>
        <el-form-item label="初始销量">
          <a-input-number
            style="width: 100%"
            :min="0"
            v-model="model.salesInitial"
            placeholder="请输入初始销量"
          ></a-input-number>
        </el-form-item>
        <!-- <el-form-item label="网店商品备注">
          <el-input v-model="model.remark" placeholder="请输入网店商品备注"></el-input>
        </el-form-item> -->
      </div>
      <div class="form_div top-label" v-if="model.specType == 10">
        <el-form-item label="网店商品重量" prop="goodsWeight" class="mr2 item_error_active">
          <div style="width: 100%; margin-top: 20px">
            <div style="display: flex; align-items: center; width: 100%">
              <a-input-number
                style="flex: 1; margin-right: 8px"
                :min="0"
                v-model="model.goodsWeight"
                placeholder="请输入网店商品重量"
              ></a-input-number>
              <span style="white-space: nowrap">千克(kg)</span>
            </div>
            <div class="form-item-tip">商品的实际重量，用于计算运费</div>
          </div>
        </el-form-item>
        <el-form-item label="运费模板" prop="deliveryId">
          <a-select v-model="model.deliveryId" :getPopupContainer="getPopupContainer" placeholder="请选择运费模板" @change="clearValidate('deliveryId')" ref="deliverySelect">
            <a-select-option v-for="item in deliveryList" :key="item.deliveryId" :value="item.deliveryId">
              {{item.name}}
            </a-select-option>
          </a-select>
          &emsp;
        </el-form-item>
        <el-form-item label="网店商品备注">
          <el-input v-model="model.remark" placeholder="请输入网店商品备注"></el-input>
        </el-form-item>
      </div>
      <!-- 多规格  class="form_div"-->
      <div style="width: 100%; display: flex" v-if="model.specType == 20">
        <div style="flex: 1">
          <div class="form_div">
            <el-form-item label="规格类型" prop="specType" class="ml0">
              <a-radio-group v-model="model.specType">
                <a-radio :value="10">单规格</a-radio>
                <a-radio :value="20">多规格</a-radio>
              </a-radio-group>
            </el-form-item>
          </div>

          <!-- 产品标注去掉 -->
          <!-- <div class="form_div">   
            <el-form-item label="校验不同规格商品价格比率一致" prop="specType" class="ml0">
              <a-radio-group v-model="model.checkType">
                <a-radio :value="0">不效验</a-radio>
                <a-radio :value="1">进行效验</a-radio>
              </a-radio-group>
            </el-form-item>
          </div> -->

          <div class="form_div">
            <el-form-item label="效验SKU长度" class="ml0" prop="skuCheckLength">
              <a-input-number
                style="width: 100%"
                v-model="model.skuCheckLength"
                :min="0"
                placeholder="请输入效验SKU长度"
              ></a-input-number>
            </el-form-item>
          </div>

          <div class="form_div">
            <el-form-item label="网店商品备注" class="ml0">
              <el-input v-model="model.remark" placeholder="请输入网店商品备注"></el-input>
            </el-form-item>
          </div>
        </div>
        <div style="flex: 1"></div>
        <div style="flex: 1">
          <div class="form_div">
            <el-form-item label="库存计算方式" prop="deductStockType" class="ml0">
              <a-radio-group v-model="model.deductStockType">
                <a-radio :value="10">下单减库存</a-radio>
                <a-radio :value="20">付款减库存</a-radio>
              </a-radio-group>
            </el-form-item>
          </div>

          <div class="form_div">
            <el-form-item label="运费模板" prop="deliveryId" class="ml0">
              <a-select v-model="model.deliveryId" :getPopupContainer="getPopupContainer" placeholder="请选择运费模板" ref="deliverySelect2">
                <a-select-option v-for="item in deliveryList" :key="item.deliveryId" :value="item.deliveryId">
                  {{item.name}}
                </a-select-option>
              </a-select>
            </el-form-item>
          </div>

          <div class="form_div">
            <el-form-item label="初始销量" class="ml0">
              <a-input-number
                style="width: 100%"
                :min="0"
                v-model="model.salesInitial"
                placeholder="请输入初始销量"
              ></a-input-number>
            </el-form-item>
          </div>
        </div>
      </div>
      <MultiSpec 
        v-if="model.specType == 20"
        style="margin-top: 20px" 
        ref="MultiSpec" 
        :defaultSpecList="this.model.specList || []"
        :defaultSkuList="this.model.goodsSkuList || []"
      />

      <div class="online_store_header">更多设置 <a-switch style="margin-left: 10px" v-model="moreSwitch" /></div>

      <!-- 更多 -->
      <div style="width: 100%; display: flex" v-show="moreSwitch">
        <div class="more-left">
          <el-form-item label="主图视频" class="more-left-item">
            <div style="width: 100%">
              <div style="display: flex; align-items: center; width: 100%">
                <el-upload
                  v-if="!videoUrl"
                  class="uploader"
                  :action="uploadAction"
                  :on-success="handleSuccessVideo"
                  :headers="headers"
                  :show-file-list="false"
                  :before-upload="beforeUploadVideo"
                  list-type="picture-card"
                  :multiple="false"
                >
                  <i slot="default" class="el-icon-plus"></i>
                </el-upload>
                <div v-else style="position: relative" class="attachment_view" @click="previewVideo">
                  <el-image
                    style="width: 100%; height: 100%; border-radius: 3px;padding: 15px;"
                    src="https://fangshangqu.good-software.cn/assets/store/img/file_preview/video.png"
                  >
                  </el-image>
                  <div class="attachment_mask">
                    <img src="@/assets/att_del.png" style="width: 100%; height: 100%" @click="delImg(1)" />
                  </div>
                  <div class="attachment_mask_pre">
                    <img src="@/assets/att_pre.png" />
                  </div>
                </div>
              </div>
              <div class="form-item-tip">建议视频宽高比19:9，建议时长8-45秒</div>
            </div>
          </el-form-item>

          <el-form-item label="视频封面" class="more-left-item">
            <div style="width: 100%">
              <div style="display: flex; align-items: center; width: 100%">
                <el-upload
                  v-if="!imageUrl"
                  class="uploader"
                  :action="uploadAction"
                  :on-success="handleSuccess"
                  :headers="headers"
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                  list-type="picture-card"
                  :multiple="false"
                >
                  <i slot="default" class="el-icon-plus"></i>
                </el-upload>
                <div v-else style="position: relative" class="attachment_view">
                  <el-image
                    style="width: 100%; height: 100%; border-radius: 3px"
                    :src="imageUrl"
                    :preview-src-list="[imageUrl]"
                  >
                  </el-image>
                  <div class="attachment_mask">
                    <img src="@/assets/att_del.png" style="width: 100%; height: 100%" @click="delImg(2)" />
                  </div>
                  <div class="attachment_mask_pre">
                    <img src="@/assets/att_pre.png" />
                  </div>
                </div>
              </div>
              <div class="form-item-tip">建议尺寸：750像素*750像素</div>
            </div>
          </el-form-item>

          <el-form-item label="商品卖点" class="more-left-item">
            <div style="width: 100%">
              <div style="display: flex; align-items: center; width: 100%">
                <a-input placeholder="请输入商品卖点" v-model="model.sellingPoint" />
              </div>
              <div class="form-item-tip">一句话简述，例如：此款商品美观大方 性价比较高 不容错过</div>
            </div>
          </el-form-item>

          <el-form-item label="服务与承诺" class="more-left-item">
            <div style="width: 100%">
              <a-select style="width: 100%" mode="multiple" v-model="model.goodsServiceIdList" :getPopupContainer="getPopupContainer" placeholder="请选择服务与承诺" ref="serviceSelect">
                <a-select-option v-for="item in serviceList" :key="item.serviceId" :value="item.serviceId">
                  {{item.name}}
                </a-select-option>
              </a-select>
              <div style="color: rgb(28, 147, 255);cursor: pointer;">
                <span @click="openCategoryDialog(2)">去新增</span>
                <span style="margin-left: 20px" @click="refreshCategory(2)">刷新</span>
              </div>
            </div>
          </el-form-item>
        </div>

        <div class="more-right">
          <a-divider orientation="left">积分设置</a-divider>
          <div class="form_div">
            <el-form-item label="积分赠送" prop="isPointsGift" class="ml13 item_error_active">
              <div style="width: 100%; margin-top: 20px">
                <div style="display: flex; align-items: center; width: 100%">
                  <a-radio-group v-model="model.isPointsGift">
                    <a-radio :value="1">开启</a-radio>
                    <a-radio :value="0">关闭</a-radio>
                  </a-radio-group>
                </div>
                <div class="form-item-tip">开启后用户购买此商品将获得积分</div>
              </div>
            </el-form-item>
          </div>
          <div class="form_div">
            <el-form-item label="积分抵扣" prop="isPointsDiscount" class="ml13 item_error_active">
              <div style="width: 100%; margin-top: 20px">
                <div style="display: flex; align-items: center; width: 100%">
                  <a-radio-group v-model="model.isPointsDiscount">
                    <a-radio :value="1">开启</a-radio>
                    <a-radio :value="0">关闭</a-radio>
                  </a-radio-group>
                </div>
                <div class="form-item-tip">开启后用户购买此商品可以使用积分进行抵扣</div>
              </div>
            </el-form-item>
          </div>
          <!-- <a-divider orientation="left">会员折扣设置</a-divider> -->

          <!-- <div class="form_div">
            <el-form-item label="会员折扣" prop="isEnableGrade" class="ml13 item_error_active">
              <div style="width: 100%; margin-top: 20px">
                <div style="display: flex; align-items: center; width: 100%">
                  <a-radio-group v-model="model.isEnableGrade">
                    <a-radio :value="1">开启</a-radio>
                    <a-radio :value="0">关闭</a-radio>
                  </a-radio-group>
                </div>
                <div class="form-item-tip">开启后会员折扣，会员购买此商品可以享受会员等级折扣价</div>
              </div>
            </el-form-item>
          </div> -->

          <a-divider orientation="left">分销设置</a-divider>

          <div class="form_div">
            <el-form-item label="分销佣金" prop="isIndDealer" class="ml13 item_error_active">
              <div style="width: 100%; margin-top: 20px">
                <div style="display: flex; align-items: center; width: 100%">
                  <a-radio-group v-model="model.isIndDealer">
                    <a-radio :value="0">系统默认</a-radio>
                    <a-radio :value="1">单独设置</a-radio>
                  </a-radio-group>
                </div>
                <div class="form-item-tip">若使用分销功能必须在 [分销中心 - 分销设置] 中开启</div>
              </div>
            </el-form-item>
          </div>

          <div class="form_div" v-if="model.isIndDealer == 1">
            <el-form-item label="分销佣金类型" class="ml13 item_error_active">
              <a-radio-group v-model="model.dealerMoneyType">
                <a-radio :value="10">百分比</a-radio>
                <a-radio :value="20">固定金额</a-radio>
              </a-radio-group>
              <!-- 分销等级列表 -->
            </el-form-item>
          </div>
          <div v-if="model.isIndDealer == 1" style="margin-left: 19%">
            <el-form-item class="ml13 item_error_active">
              <InputNumberGroup
                addonBefore="一级佣金"
                :addonAfter="model.dealerMoneyType == 10 ? '%' : '元'"
                :inputProps="{ min: 0, precision: 2 }"
                v-model="model.firstMoney"
                :rules="[{ required: true, message: '一级佣金不能为空' }]"
              />
              <InputNumberGroup
                addonBefore="二级佣金"
                :addonAfter="model.dealerMoneyType == 10 ? '%' : '元'"
                :inputProps="{ min: 0, precision: 2 }"
                v-model="model.secondMoney"
                :rules="[{ required: true, message: '二级佣金不能为空' }]"
              />
              <InputNumberGroup
                addonBefore="三级佣金"
                :addonAfter="model.dealerMoneyType == 10 ? '%' : '元'"
                :inputProps="{ min: 0, precision: 2 }"
                v-model="model.thirdMoney"
                :rules="[{ required: true, message: '三级佣金不能为空' }]"
              />
            </el-form-item>
          </div>
        </div>
      </div>
    </el-form>
    <!-- 分类弹框 -->
    <DialogCategory ref="categoryDialogRef"></DialogCategory>
    <DialogService ref="serviceDialogRef"></DialogService>
    
    <!-- 视频预览模态框 -->
    <el-dialog
      title="视频预览"
      :visible.sync="videoPreviewVisible"
      width="640px"
      :before-close="closeVideoPreview"
      append-to-body
    >
      <video v-if="videoUrl" style="width: 100%;" controls>
        <source :src="videoUrl" type="video/mp4">
        您的浏览器不支持 video 标签。
      </video>
    </el-dialog>
  </div>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import JEditor from '@/components/jeecg/JEditor'
import JImageUpload from '@/components/jeecg/JShopImageUpload'
import JImageUpload1 from '@/components/jeecg/JImageUpload'
import InputNumberGroup from '@/components/InputNumberGroup/InputNumberGroup.vue'
import { ACCESS_TOKEN, ACCOUNT_BOOK } from '@/store/mutation-types'
import DialogCategory from '../../components/dialogCategory'
import DialogService from '../../components/dialogService'
import Vue from 'vue'
import MultiSpec from './MultiSpec.vue' // 导入多规格组件，确保导入的是.vue文件

/**
 * 网店商品表单组件
 * 在此模式下，该组件不再直接提交数据到后端，而是作为表单收集网店商品信息
 * 通过事件将数据传递给父组件，由父组件统一提交
 * 
 * 使用方法：
 * 1. 通过ref调用getYoshopGoodsData()方法获取表单数据
 * 2. 监听submit-yoshop-goods事件获取表单提交的数据
 * 3. 通过ref调用resetForm()方法重置表单
 */
export default {
  name: 'onlineStoreProducts',
  components: {
    JEditor,
    JImageUpload,
    JImageUpload1,
    InputNumberGroup,
    DialogCategory,
    DialogService,
    MultiSpec, // 注册多规格组件
  },
  props: {
    //表单禁用
    // disabled: {
    //   type: Boolean,
    //   default: false,
    //   required: false
    // }
    categoryList: {
      // 商品分类列表
      type: Array,
      default: () => [],
      required: false,
    },
    // 运费模板列表
    deliveryList: {
      type: Array,
      default: () => [],
      required: false,
    },
    // 商品单位
    jbdwOptions: {
      type: Array,
      default: () => [],
      required: false,
    },
    // 服务与承诺列表
    serviceList: {
      type: Array,
      default: () => [],
      required: false,
    },
    // 进销存商品名称，用于校验
    jxcGoodsName: {
      type: String,
      default: '',
    },
    // 是否显示遮罩层
    isDetails: {
      type: Boolean,
      default: false,
    },
    getPopupContainer: {
      type: Function,
      default: (node) => node.parentNode
    }
  },
  data() {
    return {
      uploadAction: window._CONFIG['domianURL'] + '/goods/yoshopGoods/importFile',
      model: {
        goodsName: '', // 商品名称
        categoryId: undefined, // 商品分类
        status: 10, // 商品状态
        sort: 100, // 商品排序值
        unitId: undefined, // 商品单位
        content: '', // 商品详情
        specType: 10, // 规格类型
        deductStockType: 10, // 库存计算方式
        salesInitial: 0, // 初始销量
        deliveryId: undefined, // 运费模板
        remark: '', // 商品备注
        storeId: '', // 网店ID

        // 单规格
        linePrice: 0, // 商品原价 单规格
        goodsWeight: 0, // 商品重量 单规格
        stockNum: 99999999, // 商品库存 单规格
        goodsPrice: 1, // 商品优惠价 单规格

        // 多规格
        // checkType: 0, // 校验不同规格商品价格比率一致   产品标注去掉
        skuCheckLength: 0, // 效验SKU长度

        // 更多设置
        isPointsGift: 0, // 积分赠送
        isPointsDiscount: 0, // 积分抵扣
        isEnableGrade: 0, // 会员折扣
        isIndDealer: 0, // 是否开启分销
        dealerMoneyType: 10, // 分销佣金类型
        videoId: '', // 主图视频
        videoCoverId: '', // 视频封面
        sellingPoint: '', // 商品卖点
        goodsServiceIdList: [], // 服务与承诺
        moreStatus: 0, // 更多设置状态
        firstMoney: '', // 一级佣金
        secondMoney: '', // 二级佣金
        thirdMoney: '', // 三级佣金
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
        goodsName: [{ required: true, message: '请输入网店商品名称', trigger: 'blur' }],
        categoryId: [{ required: true, message: '请选择网店商品分类', trigger: 'blur' }],
        status: [{ required: true, message: '请选择商品状态', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入网店商品排序值', trigger: 'blur' }],
        unitId: [{ required: true, message: '请选择商品单位', trigger: 'blur' }],
        content: [{ required: true, message: '请输入图文信息', trigger: 'blur' }],
        specType: [{ required: true, message: '请选择规格类型', trigger: 'blur' }],
        deductStockType: [{ required: true, message: '请选择库存计算方式', trigger: 'blur' }],
        goodsPrice: [
          {
            required: true,
            message: '请输入网店商品优惠价',
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (this.model.specType !== 10) {
                callback()
                return
              }
              if (!value) {
                callback(new Error('请输入网店商品优惠价'))
              } else {
                callback()
              }
            },
          },
        ],
        goodsWeight: [
          {
            required: true,
            message: '请输入网店商品重量',
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (this.model.specType !== 10) {
                callback()
                return
              }
              if (value === undefined || value === null) {
                callback(new Error('请输入网店商品重量'))
              } else {
                callback()
              }
            },
          },
        ],
        deliveryId: [{ required: true, message: '请选择运费模板', trigger: 'blur' }],

        skuCheckLength: [{ required: true, message: '请输入效验SKU长度', trigger: 'blur' }],

        // 更多设置
        isPointsGift: [{ required: true, message: '请选择积分赠送', trigger: 'blur' }],
        isPointsDiscount: [{ required: true, message: '请选择积分抵扣', trigger: 'blur' }],
        isEnableGrade: [{ required: true, message: '请选择会员折扣', trigger: 'blur' }],
        isIndDealer: [{ required: true, message: '请选择是否开启分销', trigger: 'blur' }],
      },
      url: {
        add: '/goods/yoshopGoods/add',
        edit: '/goods/yoshopGoods/edit',
        queryById: '/goods/yoshopGoods/queryById',
      },
      moreSwitch: false,

      imageUrl: '', // 视频封面
      videoUrl: '', // 主图视频
      isGoodsNameConsistent: true, // 商品名称一致性标记
      
      videoPreviewVisible: false, // 视频预览模态框显示状态
    }
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    const token = Vue.ls.get(ACCESS_TOKEN)
    let accountBookId = Vue.ls.get(ACCOUNT_BOOK).id
    this.headers = { 'X-Access-Token': token, 'storeId': accountBookId }
    this.model.storeId = accountBookId
    
  },
  mounted () {
    // 初始化默认选中的服务与承诺
    this.initDefaultServices()
  },
  watch: {
    'model.goodsName': {
      handler(newVal) {
        // 监听网店商品名称变化，与进销存商品名称比较
        this.checkGoodsNameConsistency()
      },
      immediate: true,
    },
    jxcGoodsName: {
      handler(newVal) {
        // 监听进销存商品名称变化，与网店商品名称比较
        this.checkGoodsNameConsistency()
      },
      immediate: true,
    },
    serviceList: {
      handler(newVal) {
        if(newVal && newVal.length > 0) {
          this.initDefaultServices();
        }
      },
      immediate: true
    },
  },
  methods: {
    // 检查商品名称一致性
    checkGoodsNameConsistency() {
      if (this.jxcGoodsName && this.model.goodsName) {
        this.isGoodsNameConsistent = this.jxcGoodsName === this.model.goodsName
      } else {
        this.isGoodsNameConsistent = true
      }
    },
    // 初始化默认选中的服务与承诺
    initDefaultServices() {
      // 如果是编辑状态（model中有goodsId），则不需要初始化默认服务
      if (this.model.goodsId) {
        return;
      }
      
      if (this.serviceList && this.serviceList.length > 0) {
        const defaultServiceIds = this.serviceList.filter((item) => item.isDefault === 1).map((item) => item.serviceId)
        if (defaultServiceIds.length > 0) {
          this.model.goodsServiceIdList = defaultServiceIds
        }
      }
    },

    add() {
      this.edit(this.modelDefault)
    },
    edit(record) {
      // 创建深拷贝而不是浅拷贝
      this.model = JSON.parse(JSON.stringify(record))
      
      // 单规格数据处理
      if (this.model.specType === 10 && this.model.goodsSku) {
        // 使用解构赋值并用$set确保响应式
        const { linePrice = 0, goodsPrice = 1, stockNum = 99999, goodsWeight = 0 } = this.model.goodsSku || {}
        this.$set(this.model, 'linePrice', linePrice)
        this.$set(this.model, 'goodsPrice', goodsPrice)
        this.$set(this.model, 'stockNum', stockNum)
        this.$set(this.model, 'goodsWeight', goodsWeight)
      } else if (this.model.specType == 20 && this.model.goodsSkuList) {
        this.$set(this.model, 'skuCheckLength', 0)
        this.model.goodsSkuList.forEach(sku => {
          sku.goodsProps = JSON.parse(sku.goodsProps)
          sku.specValueIds = JSON.parse(sku.specValueIds)
        })
      }
      
      // 处理主图视频数据回显
      if (this.model.video && this.model.video.length > 0) {
        const videoData = this.model.video[0]
        this.videoUrl = videoData.filePath
        this.$set(this.model, 'videoId', videoData.fileId)
      }
      
      // 处理视频封面数据回显
      if (this.model.videoCover && this.model.videoCover.length > 0) {
        const coverData = this.model.videoCover[0]
        this.imageUrl = coverData.filePath
        this.$set(this.model, 'videoCoverId', coverData.fileId)
      }
      
      // 处理服务与承诺数据回显
      if (this.model.goodsServiceList && this.model.goodsServiceList.length > 0) {
        this.$set(this.model, 'goodsServiceIdList', this.model.goodsServiceList.map(item => item.serviceId))
      }

      this.moreSwitch = this.model.moreStatus == 1
      
      // 编辑时检查商品名称一致性
      this.$nextTick(() => {
        this.checkGoodsNameConsistency()
      })
    },

    // 刷新商品分类
    refreshCategory(type) {
      if (type == 1) {
        // 改为set方法赋值
        this.$set(this.model, 'categoryId', undefined)
        // this.model.categoryId = undefined
        this.$emit('refreshCategory')
      } else if (type == 2) {
        // 改为set方法赋值
        this.$set(this.model, 'goodsServiceIdList', [])
        // this.model.goodsServiceIdList = []
        this.$emit('refreshService')
      }
    },

    submitForm(goodsId) {
      const that = this
      // 触发表单验证
      const validateResult = this.validateForm();
      if (validateResult.valid) {
        // 设置更多设置状态
        this.model.moreStatus = this.moreSwitch ? 1 : 0

        // 设置关联的商品ID (如果有)
        if (goodsId) {
          this.model.xghJxcGoodsId = goodsId
        }
        
        if (this.model.goodsId) {
          // 编辑时清除这些字段
          delete this.model.goodsSkuList
          delete this.model.specList
        }
        
        // 准备好数据后，通过事件发送给父组件
        const yoshopGoodsData = JSON.parse(JSON.stringify(this.model))
        this.$emit('submit-yoshop-goods', yoshopGoodsData)
        
        return true
      } else {
        // 显示具体的错误信息
        if (validateResult.errorMsg) {
          that.$elMessage.error(validateResult.errorMsg)
        }
        return false
      }
    },
    
    // 获取网店商品数据，供父组件调用
    getYoshopGoodsData() {
      const validateResult = this.validateForm();
      if (validateResult.valid) {
        // 设置更多设置状态
        this.model.moreStatus = this.moreSwitch ? 1 : 0
        
        // 处理多规格SKU数据
        if (this.model.goodsSkuList && this.model.goodsSkuList.length > 0) {
          this.model.goodsSkuList.forEach(sku => {
            sku.goodsProps = JSON.stringify(sku.goodsProps)
            sku.specValueIds = JSON.stringify(sku.specValueIds)
          })
        }
        // 返回数据副本
        return JSON.parse(JSON.stringify(this.model))
      }
      
      // 如果验证失败，显示错误信息
      if (validateResult.errorMsg) {
        this.$elMessage.error(validateResult.errorMsg);
      }
      
      return null
    },

    // 重置表单，供父组件调用
    resetForm() {
      // 重置表单数据
      this.model = JSON.parse(JSON.stringify(this.modelDefault))
      this.imageUrl = ''  // 清空视频封面
      this.videoUrl = ''  // 清空主图视频
      this.moreSwitch = false  // 关闭更多设置开关
      this.$refs.form.resetFields()  // 重置表单验证状态
      
      // 多规格组件也需要重置
      if (this.$refs.MultiSpec) {
        this.$refs.MultiSpec.resetForm()
      }
      
      // 重新初始化默认选中的服务与承诺
      this.initDefaultServices()
    },

    handleSuccess(e) {
      console.log(e)
      if (e.success) {
        const fileInfo = e.result
        let url = fileInfo.domain + '/' + fileInfo.filePath
        // let url = fileInfo.filePath
        this.imageUrl = url
        this.model.videoCoverId = fileInfo.fileId
      }
    },
    handleSuccessVideo(e) {
      console.log(e)
      if (e.success) {
        const fileInfo = e.result
        let url = fileInfo.domain + '/' + fileInfo.filePath
        // let url = fileInfo.filePath
        this.videoUrl = url
        this.model.videoId = fileInfo.fileId
      }
    },
    beforeUpload(file) {
      let type = file.type.toLowerCase()
      const isJPG = type.includes('png') || type.includes('jpeg') || type.includes('jpg')
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('请上传png/jpg/jpeg格式的图片!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    beforeUploadVideo(file) {
      let type = file.type.toLowerCase()
      const isMP4 = type.includes('mp4')
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isMP4) {
        this.$message.error('请上传mp4格式的视频!')
        return false
      }
      if (!isLt10M) {
        this.$message.error('上传视频大小不能超过 10MB!')
        return false
      }
      return true
    },

    delImg(val) {
      if (val === 1) {
        this.videoUrl = ''
        this.model.videoId = ''
      } else if (val === 2) {
        this.imageUrl = ''
        this.model.videoCoverId = ''
      }
    },

    // 效验表单
    validateForm() {
      let isValid = false;
      let errorMsg = '';
      
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 处理多规格数据
          if (this.model.specType === 20) {
            const MultiSpec = this.$refs.MultiSpec
            if (!MultiSpec.verifyForm()) {
              errorMsg = MultiSpec.getError() || '多规格验证失败';
              return false;
            }
            // 记录多规格数据
            this.model.specData = MultiSpec.getFromSpecData()
            // 验证SKU编码
            if (this.model.skuCheckLength > 0) {
              const isSubmit = this.validateSkuCodes()
              if (!isSubmit) {
                errorMsg = '请确认商品规格中SKU编码';
                return false;
              }
            }
            // 将对象转换为JSON字符串
            if (this.model.goodsSkuList && this.model.goodsSkuList.length > 0) {
              this.model.goodsSkuList.forEach(sku => {
                sku.goodsProps = JSON.stringify(sku.goodsProps)
                sku.specValueIds = JSON.stringify(sku.specValueIds)
              })
            }
          } else if (this.model.specType === 10) {
            // 单规格情况下，将四个参数包装到goodsSku对象中
            this.model.goodsSku = {
              ...this.model.goodsSku,
              linePrice: this.model.linePrice ? this.model.linePrice : 0,
              goodsWeight: this.model.goodsWeight,
              stockNum: this.model.stockNum,
              goodsPrice: this.model.goodsPrice
            }
          }
          if (this.model.isIndDealer != 1) {
            delete this.model.dealerMoneyType
            delete this.model.firstMoney
            delete this.model.secondMoney
            delete this.model.thirdMoney
          }
          // 在提交的时候 salesInitial什么都不输入的情况下会给后端传null  现在需要在为null的时候传0
          if (this.model.salesInitial === null) {
            this.model.salesInitial = 0
          }
          isValid = true;
        } else {
          errorMsg = '请完善网店商品信息';
        }
      })
      
      // 返回对象包含验证结果和错误信息
      return {
        valid: isValid,
        errorMsg: errorMsg
      };
    },

    // 验证多规格SKU编码
    validateSkuCodes() {
      const temp = this.model.specData.skuList
      // 获取输入的数字的长度
      let sukLength = this.model.skuCheckLength
      // 获取第一个sku
      const itemone = temp[0].goodsSkuNo
      // 获取第一个sku的长度
      const itemoneLength = itemone.length

      if (sukLength >= itemoneLength) {
        // 如果输入的长度 大于 第一个sku的长度，输入的长度 赋值为 第一个sku的长度
        sukLength = itemoneLength
      }
      // 根据输入的数字，截取第一个sku的前几位，作为效验标准
      const biaozhunStr = itemone.substr(0, sukLength)

      for (let i = 1; i < temp.length; i++) {
        // 获取当前完整sku
        const skuAll = temp[i].goodsSkuNo
        // 从完整sku中截取，相应部分
        const skuStr = skuAll.substr(0, sukLength)
        // 截取后的sku与效验标准对比
        if (biaozhunStr !== skuStr) {
          return false
        }
      }
      return true
    },
    openCategoryDialog(type) {
      if (type === 1) {
        this.$emit('refreshCategory')
        this.$refs.categoryDialogRef.dialogVisible = true
      } else if (type === 2) {
        this.$emit('refreshService')
        this.$refs.serviceDialogRef.dialogVisible = true
      }
    },
    // 网店商品名称变化时触发事件
    onGoodsNameChange() {
      // 触发input事件通知父组件
      this.$emit('input', this.model);
      // 更新本地一致性状态
      this.checkGoodsNameConsistency();
    },
    clearValidate(prop) {
      // 清除表单验证错误信息
      if (this.$refs.form) {
        this.$refs.form.clearValidate(prop);
      }
    },
    previewVideo(event) {
      // 阻止事件冒泡，避免触发父元素的点击事件
      if (event) {
        event.stopPropagation();
      }
      console.log('this.videoUrl', this.videoUrl);
      if (this.videoUrl) {
        this.videoPreviewVisible = true;
      } else {
        this.$message.info('视频地址不存在');
      }
    },
    closeVideoPreview() {
      this.videoPreviewVisible = false;
    },
  },
}
</script>
<style lang="less" scoped>
.online-store-products {
  .online_store_header {
    font-size: 16px;
    color: #1890ff;
    display: flex;
    align-items: center;
    margin: 30px 0;
    margin-top: 70px;
  }

  .form-item-tip {
    font-size: 12px;
    color: #999;
    line-height: 1.5;
  }

  // 网店商品名称警告样式
  :deep(.name-warning .el-input__inner) {
    color: #f7a16c !important;
  }

  // .weight-input-group {
  //   display: flex;
  //   align-items: center;
  //   .unit {
  //     white-space: nowrap;
  //     margin-left: 8px;
  //     flex-shrink: 0;
  //   }
  // }
  .more-left {
    flex: 1;
    padding-right: 20px;
    .more-left-item {
      display: flex;

      ::v-deep .el-form-item__label {
        width: auto;
        min-width: 90px;
        line-height: 30px;
        font-size: 12px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #666;
        text-align: justify;
        text-justify: distribute-all-lines;
        /*ie6-8*/
        text-align-last: justify;
        /* ie9*/
        -moz-text-align-last: justify;
        /*ff*/
        -webkit-text-align-last: justify;
        /*chrome 20+*/
        position: relative;

        &::before {
          position: absolute;
          right: 0;
          margin-right: 0;
          color: #ff0000;
          font-weight: 600;
        }
      }
      ::v-deep .el-form-item__content {
        margin-left: 8px;
        flex: 1;
        // height: 30px;
        display: flex;
        align-items: center;

        .el-input {
          width: 100%;
          height: 30px;
          display: flex;
          align-items: center;

          .el-input__inner {
            height: 100% !important;
            padding: 0 0.187512rem;
            font-size: 12px;
            color: #666;
          }
        }
        .el-input__icon {
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
      ::v-deep .el-upload--picture-card {
        width: 80px;
        height: 80px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .uploader {
        width: 80px;
        height: 80px;
        overflow: hidden;
        position: relative;
      }
      .attachment_view {
        border: 1px dashed #ddd;
        width: 80px;
        height: 80px;
        background-color: #f6f6f6;
        line-height: 40px;
        text-align: center;
      }
      .attachment_mask {
        z-index: 2;
        position: absolute;
        right: 0;
        top: 0;
        width: 12px;
        height: 12px;
        display: flex;
        align-items: center;
      }
      .attachment_mask_pre {
        z-index: 1;
        position: absolute;
        display: flex;
        align-items: center;
        pointer-events: none;
        right: 0;
        top: 0;
        left: 0;
        bottom: 0;
        // backdrop-filter: blur(1px);
        img {
          position: absolute;
          width: 14px;
          height: 14px;
          transform: translate(-50%, -50%);
          top: 50%;
          left: 50%;
        }
      }
    }
  }
  .more-right {
    flex: 1;
    padding-left: 20px;
  }
}
.form_div {
  width: 100%;
  height: 30px;
  display: flex;
  margin-top: 30px;

  .line_dialog {
    ::v-deep .el-form-item__content {
      position: relative;

      > i {
        position: absolute;
        right: 0.187512rem;
        color: #bfbfbf;
      }
    }

    .scan_p {
      position: absolute;
      right: 0.187512rem;
      display: flex;
      align-items: center;

      > span {
        color: #1890ff;
        margin-left: 0.093756rem;
      }
    }
  }

  .spmc_div {
    ::v-deep .el-form-item__content {
      flex: 1;
      // .el-input {
      //   width: calc(100% - 1.031314rem);
      //   .el-input__inner {
      //     border-radius: 0.075005rem 0 0 0.075005rem;
      //     border-right: none;
      //   }
      // }
      // .el-button {
      //   width: 1.031314rem;
      //   height: 30px;
      //   display: flex;
      //   align-items: center;
      //   justify-content: center;
      //   font-size: 12px;
      //   background: #1890ff;
      //   border-radius: 0 0.075005rem 0.075005rem 0;
      // }
    }
  }

  .disable_input {
    ::v-deep .el-input__inner {
      background-color: #ededed;
      border: 1px solid #e3e3e3;
      border-radius: 0.075005rem;
      font-size: 12px;
      font-family: PingFang SC;
      font-weight: 400;
      color: #666666;
    }
  }

  ::v-deep .el-form-item {
    display: flex;
    width: 100%;
    margin-bottom: 0;
    .el-form-item__label {
      width: auto;
      min-width: 90px;
      line-height: 30px;
      font-size: 12px;
      font-family: PingFang SC;
      font-weight: 400;
      color: #666;
      text-align: justify;
      text-justify: distribute-all-lines;
      /*ie6-8*/
      text-align-last: justify;
      /* ie9*/
      -moz-text-align-last: justify;
      /*ff*/
      -webkit-text-align-last: justify;
      /*chrome 20+*/
      position: relative;

      &::before {
        position: absolute;
        right: 0;
        margin-right: 0;
        color: #ff0000;
        font-weight: 600;
      }
    }

    .el-form-item__content {
      margin-left: 8px;
      flex: 1;
      height: 30px;
      display: flex;
      align-items: center;

      .el-input {
        width: 100%;
        height: 30px;
        display: flex;
        align-items: center;

        .el-input__inner {
          height: 100%;
          padding: 0 0.187512rem;
          font-size: 12px;
          color: #666;
        }
      }
    }

    // &:first-child {
    //   margin-right: 10px;
    // }

    &:last-child {
      margin-left: 2%;
    }
  }
  div {
    p {
      margin: 0;
      font-size: 12px;
      font-family: PingFang SC;
      font-weight: 400;
      color: #666666;
    }

    input {
      flex: 1;
      height: 30px;
      background: #ffffff;
      border: 1px solid #e3e3e3;
      border-radius: 0.075005rem;
      font-size: 12px;
      color: #666;
      box-sizing: border-box;
      padding: 0 0.187512rem;

      &:focus {
        outline: none;
        border-color: #1890ff;
      }
    }

    ::v-deep .el-select {
      flex: 1;

      .el-input {
        .el-input__inner {
          height: 30px;
          background: #ffffff;
          border: 1px solid #e3e3e3;
          border-radius: 0.075005rem;
          font-size: 12px;
          color: #666;
          box-sizing: border-box;
          padding: 0 0.187512rem;
        }

        .el-input__suffix {
          height: 30px;
          display: flex;
          align-items: center;
        }
      }
    }
  }
}

.layoutOne {
  flex: 2;
}
.layoutTwo {
  flex: 1;
  ::v-deep .el-form-item__content {
    flex-direction: column;
    align-items: flex-start !important;
  }
}
.ml0 {
  margin-left: 0 !important;
}
.ml13 {
  margin-left: 13% !important;
}
.mr2 {
  margin-right: 2% !important;
}
.align-flex-start {
  align-items: flex-start !important;
}
.top-label {
  ::v-deep .el-form-item {
    .el-form-item__content {
      height: auto;
    }
    // &:last-child {
    //   margin-left: 0%;
    // }
  }
}

.item_error_active {
  ::v-deep .el-form-item__error {
    top: 170%;
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
// 分割线
::v-deep .ant-divider {
  margin: 30px 0 !important;

  .ant-divider-inner-text {
    font-size: 13px;
    color: rgba(0, 0, 0, 0.61);
  }
}

::v-deep .ant-radio-wrapper {
  font-weight: normal;
  color: rgba(0, 0, 0, 0.5);
}

// ::v-deep .ant-radio-inner {
//   display: flex;
//   align-items: center;
//   justify-content: center;
// }

.form-item-help {
  cursor: pointer;
  color: rgb(28, 147, 255);
  line-height: 55px;
}
.content_div {
  width: 121px;
  height: 215px;
  position: absolute;
  top: 60px;
  left: 20px;
  background-color: #fff;
  line-height: initial;
  overflow: auto;
}
</style>
